import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login } from '@/api/apis.js'

export const useUserStore = defineStore('user_uni', () => {
  // 用户信息
  const user = ref({});
  // 访客token
  const authentication = ref('')

  // 获取用户信息
  const getUserInfo = async (data) => {
    const res = await login(data)
    console.log(res);
    // 存储起来
    user.value = res.data
    authentication.value = res.data.token
    // 关闭旧的 WebSocket 连接
    getApp().closeSocket();

    // 建立新的 WebSocket 连接
    getApp().ws(user.value.id);
  }

  // 清除用户信息
  const clearUserInfo = async () => {
    // await logout()
    clear()
  }

  const clear = () => {
    user.value = {}
    authentication.value = ''
  }

  // 暴露出去
  return {
    user,
    getUserInfo,
    clearUserInfo,
    clear,
    authentication
  }
}, {
  // 配置持久化
  persist: {
    // 调整为兼容多端的API
    storage: {
      setItem(key, value) {
        uni.setStorageSync(key, value)
      },
      getItem(key) {
        return uni.getStorageSync(key)
      },
    },
  },
})
